﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

using ExcelCOM = Microsoft.Office.Interop.Excel;

namespace HITs
{
    class ShareData
    {
        public static DanhSachCoPhieu danhsachCoPhieu = new DanhSachCoPhieu();
               
        /// <summary>
        /// Lấy những cổ phiếu có số lượng giá cổ phiếu đầy đủ (từ đầu) theo danh sách tên cổ phiếu
        /// </summary>
        public static DanhSachCoPhieu Get_CoPhieu(List<string> danhsachTenCP)
        {
            DanhSachCoPhieu result = new DanhSachCoPhieu();
            foreach(string tenCP in danhsachTenCP)
                foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                    if (tenCP == cp.TenCoPhieu)
                    {
                        result.Xuly_ThemCoPhieu(cp);
                        break;
                    }
            return result;
        }

        public static void LoaiboDongDuLieuDu()
        {
            FileStream fs = new FileStream(System.Windows.Forms.Application.StartupPath + @"\Data\MetaStock_HOSE.txt"
                , FileMode.Open);
            StreamReader reader = new StreamReader(fs, Encoding.UTF8);
            List<string> listContent = new List<string>();
            string beforeStr = "";
            string str = "";
            while (reader.EndOfStream != true)
            {
                str = reader.ReadLine();
                if (str != "" && str != beforeStr)
                {
                    listContent.Add(str);
                    beforeStr = str;
                }
            }
            reader.Close();
            fs.Close();

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\MetaStock_HOSE_sub.txt", listContent);
        }

        public static void Testing_In_SoNgayGiaoDichVNIndex(int step = 3)
        {
            List<string> listFile = new List<string>();
            foreach(CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    for (int i = 0; i < cp.DanhSachNgayGiaoDich.Count - step; i += step)                    
                        listFile.Add(cp.DanhSachNgayGiaoDich[i].NgayGiaoDich_Str);
                    
                }
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\Test_InDanhSachNgayVNINDEX.txt", listFile);
        }
               
        public static void Testing_BackTest_HistorgramMACD(List<string> listCP)
        {
            List<float> signalLine = new List<float>();
            List<float> listChechLech = new List<float>();
            List<float> MACD = new List<float>();

            List<List<float>> listlistValue = new List<List<float>>();
       
          
            List<float> listValue = new List<float>();

            foreach(CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (listCP.Contains(cp.TenCoPhieu))
                {
                    signalLine = new List<float>();
                    listChechLech = new List<float>();
                    MACD = new List<float>();
                    Indicators.MACD(cp.DanhSachGiaDongCua_DieuChinh, 12, 26, 9, ref MACD, ref signalLine);

                    for (int i = 0; i < MACD.Count && i < signalLine.Count; i++)
                        listChechLech.Add(MACD[i] - signalLine[i]);

                    listValue = new List<float>();

                    for (int i = 0; i < listChechLech.Count - 2; i++)
                    {
                        if ((listChechLech[i] >= 0 && listChechLech[i + 1] <= 0)
                            || (listChechLech[i] <= 0 && listChechLech[i + 1] >= 0))
                        {
                            if (listValue.Count != 0)
                                listlistValue.Add(new List<float>(listValue));
                            listValue = new List<float>();
                        }
                        listValue.Add(listChechLech[i + 1]);
                    }
                }

            List<string> listGhiFile = new List<string>();
            string row = "";
            foreach (List<float> listVal in listlistValue)
            {
                row = "";
                foreach (float val in listVal)                
                    row += Math.Round(val, 3).ToString() + "  ";
                
                listGhiFile.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\BackTest_HistogramMACD.txt"
                , listGhiFile);
        }

        public static void Testing_BackTest_HistorgramMACD_SoDinh(List<string> listCP)
        {
            List<float> signalLine = new List<float>();
            List<float> listChechLech = new List<float>();
            List<float> MACD = new List<float>();

            List<List<int>> listlistValue = new List<List<int>>();
            List<int> listDinh = new List<int>();
            List<float> listValue = new List<float>();
            int soDinh = 0;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (listCP.Contains(cp.TenCoPhieu))
                {
                    signalLine = new List<float>();
                    listChechLech = new List<float>();
                    listValue = new List<float>();
                    listDinh = new List<int>();
                    MACD = new List<float>();
                    Indicators.MACD(cp.DanhSachGiaDongCua_DieuChinh, 12, 26, 9, ref MACD, ref signalLine);

                    for (int i = 0; i < MACD.Count && i < signalLine.Count; i++)
                        listChechLech.Add(MACD[i] - signalLine[i]);
                                      

                    for (int i = 0; i < listChechLech.Count - 2; i++)
                    {
                        if ((listChechLech[i] >= 0 && listChechLech[i + 1] <= 0)
                            || (listChechLech[i] <= 0 && listChechLech[i + 1] >= 0))
                        {
                            if (listValue.Count != 0)
                            {
                                soDinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listValue, 3);
                                if(listValue[0] < 0) 
                                    soDinh = soDinh* -1;
                                listDinh.Add(soDinh);
                            }
                            listValue = new List<float>();
                        }
                        listValue.Add(listChechLech[i + 1]);
                    }

                    if (listDinh.Count != 0)
                        listlistValue.Add(listDinh);
                }

            List<string> listGhiFile = new List<string>();
            string row = "";
            foreach (List<int> listval in listlistValue)
            {
                row ="";
                foreach(int val in listval)
                    row += val.ToString() + "  ";
                if(row != "")
                    listGhiFile.Add(row);
            }           
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\BackTest_HistogramMACD_SoDinh.txt"
                , listGhiFile);
        }

        public static void Testing_BackTest_HistorgramMACD_SoNgay(List<string> listCP)
        {
            List<float> signalLine = new List<float>();
            List<float> listChechLech = new List<float>();
            List<float> MACD = new List<float>();

            List<List<int>> listlistValue = new List<List<int>>();
            List<int> listDinh = new List<int>();
            List<float> listValue = new List<float>();
            int soDinh = 0;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (listCP.Contains(cp.TenCoPhieu))
                {
                    signalLine = new List<float>();
                    listChechLech = new List<float>();
                    listValue = new List<float>();
                    listDinh = new List<int>();
                    MACD = new List<float>();
                    Indicators.MACD(cp.DanhSachGiaDongCua_DieuChinh, 12, 26, 9, ref MACD, ref signalLine);

                    for (int i = 0; i < MACD.Count && i < signalLine.Count; i++)
                        listChechLech.Add(MACD[i] - signalLine[i]);


                    for (int i = 0; i < listChechLech.Count - 2; i++)
                    {
                        if ((listChechLech[i] >= 0 && listChechLech[i + 1] <= 0)
                            || (listChechLech[i] <= 0 && listChechLech[i + 1] >= 0))
                        {
                            if (listValue.Count != 0)
                            {
                                soDinh = listValue.Count;
                                if (listValue[0] < 0)
                                    soDinh = soDinh * -1;
                                listDinh.Add(soDinh);
                            }
                            listValue = new List<float>();
                        }
                        listValue.Add(listChechLech[i + 1]);
                    }

                    if (listDinh.Count != 0)
                        listlistValue.Add(listDinh);
                }

            List<string> listGhiFile = new List<string>();
            string row = "";
            foreach (List<int> listval in listlistValue)
            {
                row = "";
                foreach (int val in listval)
                    row += val.ToString() + "  ";
                if (row != "")
                    listGhiFile.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\BackTest_HistogramMACD_SoNgay.txt"
                , listGhiFile);
        }

        public static void Testing_BackTest_MACD_Statistic(List<string> listCP)
        {
            List<float> signalLine = new List<float>();
            List<float> listChechLech = new List<float>();
            List<float> MACD = new List<float>();

            List<List<float>> listlistValue = new List<List<float>>();
            
            List<float> listValue = new List<float>();

            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (listCP.Contains(cp.TenCoPhieu))
                {
                    signalLine = new List<float>();
                    listChechLech = new List<float>();
                    MACD = new List<float>();
                    Indicators.MACD(cp.DanhSachGiaDongCua_DieuChinh, 12, 26, 9, ref MACD, ref signalLine);

                    listValue = new List<float>();
                    listChechLech = MACD;
                }

            List<string> listGhiFile = new List<string>();
            string row = "";
            foreach (List<float> listVal in listlistValue)
            {
                row = "";
                foreach (float val in listVal)
                    row += Math.Round(val, 3).ToString() + "  ";

                listGhiFile.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\BackTest_ListMACD.txt"
                , listGhiFile);
        }

        public static void Testing_BackTest_HistorgramMACD_Statistic()
        {
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();

            bool flag_am = false, flag_break = false ;
            float val;
            List<float> listValues_TK = new List<float>();
            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);                        
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);                           
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh, sodinhMAX = 25, soNgayCachDinh = 30;
            List<int> list_CountSoDinh_Duong = new List<int>();
            List<int> list_CountSoDinh_Am = new List<int>();
            string rowFile = "", row = "" ;
            float chechlech = 0.15f;

            for (int i = 0; i < sodinhMAX; i++)
            {
                list_CountSoDinh_Am.Add(0);
                list_CountSoDinh_Duong.Add(0);

            }
            for (int i = 1; i <= sodinhMAX; i++)
                rowFile += i.ToString() + "\t";
            
            listFile = new List<string>();

            listFile.Add("Avg strength: " + CoreFunctions.Tk_GetAverage(listValues_TK));
            listFile.Add("Std strength: " + CoreFunctions.Tk_SampleStandardDeviation(listValues_TK));

            listFile.Add("So histogram Duong: " + listDuong.Count);
            listFile.Add("So histogram Am   : " + listAm.Count);
            listFile.Add("Chech lech        : " + chechlech.ToString());
            listFile.Add("\n\n");

            listFile.Add("Histogram Duong");
            listFile.Add("Ngay-Dinh\t" + rowFile);

          
            for (int i = 1; i <= soNgayCachDinh; i = i + 2)
            {
                list_CountSoDinh_Duong = new List<int>();
                for (int j = 0; j < sodinhMAX; j++)         
                    list_CountSoDinh_Duong.Add(0);
                row = "";
                foreach (List<float> listVal in listDuong)
                {
                    sodinh = 0;
                    sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, i, chechlech);
                    if (sodinh > 0)
                    {
                        if (sodinh <= list_CountSoDinh_Duong.Count)
                            list_CountSoDinh_Duong[sodinh - 1]++;
                        else
                            list_CountSoDinh_Duong[sodinhMAX - 1]++;
                    }
                }
                foreach (int valDinh in list_CountSoDinh_Duong)
                    row += valDinh.ToString() + "\t";

                listFile.Add(i.ToString() + "\t\t" + row);
            }

            listFile.Add("\n\n");
            listFile.Add("Histogram Am");
            listFile.Add("Ngay-Dinh\t" + rowFile);
            for (int i = 1; i <= soNgayCachDinh; i = i + 2)
            {
                list_CountSoDinh_Am = new List<int>();
                for (int j = 0; j < sodinhMAX; j++)
                    list_CountSoDinh_Am.Add(0);
                row = "";

                foreach (List<float> listVal in listAm)
                {
                    sodinh = 0;
                    sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, i,chechlech);
                    if (sodinh > 0)
                    {
                        if (sodinh <= list_CountSoDinh_Am.Count)
                            list_CountSoDinh_Am[sodinh - 1]++;
                        else
                            list_CountSoDinh_Am[sodinhMAX - 1]++;
                    }
                }

                foreach (int valDinh in list_CountSoDinh_Am)
                    row += valDinh.ToString() + "\t";

                listFile.Add(i.ToString() + "\t\t" + row);
            }

            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD_Statistic.txt", listFile);
            #endregion
        }

        public static void Testing_BackTest_HistorgramMACD_Statistic_Chechlech()
        {
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;
            List<float> listValues_TK = new List<float>();
            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh, sodinhMAX = 25, chechlech = 60;
            int soNgayCachDinh = 2;
            List<int> list_CountSoDinh_Duong = new List<int>();
            List<int> list_CountSoDinh_Am = new List<int>();
            string rowFile = "", row = "";
            for (int i = 0; i < sodinhMAX; i++)
            {
                list_CountSoDinh_Am.Add(0);
                list_CountSoDinh_Duong.Add(0);

            }
            for (int i = 1; i <= sodinhMAX; i++)
                rowFile += i.ToString() + "\t";

            listFile = new List<string>();

            listFile.Add("Avg strength: " + CoreFunctions.Tk_GetAverage(listValues_TK));
            listFile.Add("Std strength: " + CoreFunctions.Tk_SampleStandardDeviation(listValues_TK));

            listFile.Add("So histogram Duong: " + listDuong.Count);
            listFile.Add("So histogram Am   : " + listAm.Count);
            listFile.Add("So ngay cach dinh : " + soNgayCachDinh);
            listFile.Add("\n");

            listFile.Add("Histogram Duong");
            listFile.Add("%CL-Dinh\t" + rowFile);

            for (int i = 1; i <= chechlech; i = i + 2)
            {
                list_CountSoDinh_Duong = new List<int>();
                for (int j = 0; j < sodinhMAX; j++)
                    list_CountSoDinh_Duong.Add(0);
                row = "";
                foreach (List<float> listVal in listDuong)
                {
                    sodinh = 0;
                    sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, i / 100f);
                    if (sodinh > 0)
                    {
                        if (sodinh <= list_CountSoDinh_Duong.Count)
                            list_CountSoDinh_Duong[sodinh - 1]++;
                        else
                            list_CountSoDinh_Duong[sodinhMAX - 1]++;
                    }
                }
                foreach (int valDinh in list_CountSoDinh_Duong)
                    row += valDinh.ToString() + "\t";

                listFile.Add(i.ToString() + "\t\t" + row);
            }
            listFile.Add("\n\n");
            listFile.Add("Histogram Am");
            listFile.Add("%CL-Dinh\t" + rowFile);
            for (int i = 1; i <= chechlech; i = i + 2)
            {
                list_CountSoDinh_Am = new List<int>();
                for (int j = 0; j < sodinhMAX; j++)
                    list_CountSoDinh_Am.Add(0);
                row = "";

                foreach (List<float> listVal in listAm)
                {
                    sodinh = 0;
                    sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, i / 100f);
                    if (sodinh > 0)
                    {
                        if (sodinh <= list_CountSoDinh_Am.Count)
                            list_CountSoDinh_Am[sodinh - 1]++;
                        else
                            list_CountSoDinh_Am[sodinhMAX - 1]++;
                    }
                }

                foreach (int valDinh in list_CountSoDinh_Am)
                    row += valDinh.ToString() + "\t";

                listFile.Add(i.ToString() + "\t\t" + row);
            }

            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD_Statistic_ChechLech.txt", listFile);
            #endregion
        }

        public static float Testing_BackTest_HistorgramMACD_Statistic_Chechlech(int soDinh, float chechlech, bool flagDuong)
        {
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;
            List<float> listValues_TK = new List<float>();
            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh, sodinhMAX = 5;
            int soNgayCachDinh = 2;
            float result = 0f;
            chechlech /= 100;
            List<int> list_CountSoDinh_Duong = new List<int>();
            List<int> list_CountSoDinh_Am = new List<int>();
            string rowFile = "";

            for (int i = 0; i < sodinhMAX; i++)
            {
                list_CountSoDinh_Am.Add(0);
                list_CountSoDinh_Duong.Add(0);

            }
            for (int i = 1; i <= sodinhMAX; i++)
                rowFile += i.ToString() + "\t";
            int sum = 0, temp = 0;
            List<List<float>> listCheck = new List<List<float>>();

            if (flagDuong)
                listCheck = listDuong;
            else
                listCheck = listAm;
            
            list_CountSoDinh_Am = new List<int>();
            for (int j = 0; j < sodinhMAX; j++)
                list_CountSoDinh_Am.Add(0);

            foreach (List<float> listVal in listCheck)
            {
                sodinh = 0;
                sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlech);
                if (sodinh > 0)
                {
                    if (sodinh <= list_CountSoDinh_Am.Count)
                        list_CountSoDinh_Am[sodinh - 1]++;
                    else
                        list_CountSoDinh_Am[sodinhMAX - 1]++;
                    sum++;
                }
            }

            for (int i = 0; i < soDinh; i++)
                temp += list_CountSoDinh_Am[i];
            result = (float)temp / sum * 100;
            result = (float)Math.Round(result, 0);
            #endregion

            return result;
        }

        public static void Testing_BackTest_HistorgramMACD_Statistic_Chechlech_SoNgay()
        {
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistorgramMACD_DieuChinh.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();
            List<float> listValues_TK = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;

            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int soDinhMAX = 5, soDinhCheck;
            List<int> listResult = new List<int>();
            listFile = new List<string>();
            for(soDinhMAX = 5; soDinhMAX < 15; soDinhMAX = soDinhMAX + 1)
                for (soDinhCheck = 1; soDinhCheck < soDinhMAX; soDinhCheck++)
                {
                    listResult = Testing_BackTest_HistorgramMACD_Statistic_Chechlech_SoNgay(listDuong, listAm, soDinhMAX, soDinhCheck);
                    listFile.Add("So Dinh MAX: " + soDinhMAX + "\t\t" + "So Dinh Check: " + soDinhCheck);
                    listFile.Add("*DUONG: " + "So ngay: " + listResult[0] + "\t\tChech lech: " 
                        + listResult[1] + "\tChinh xac: " + listResult[2]);
                    listFile.Add("*AM:    " + "So ngay: " + listResult[3] + "\t\tChech lech: " 
                        + listResult[4] + "\tChinh xac: " + listResult[5]);
                    listFile.Add("\n---------------------------------\n");
                }
            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD_Statistic_ChechLech_SoNgay.txt", listFile);
            #endregion
        }

        public static List<int> Testing_BackTest_HistorgramMACD_Statistic_Chechlech_SoNgay(int soDinhMAX, int soDinhCheck)
        {
            /// Return list 2 giá trị: 
            /// [0], [1] = max phần sóng dương (số ngày - chêch lệch)
            /// [2], [3] = max phần sóng âm    (số ngày - chêch lệch)
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();
            List<float> listValues_TK = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;

            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh,
                soNgayCachDinhMAX = 15,
                chechlechMAX = 50,
                soSongDuong = listDuong.Count,
                soSongAm = listAm.Count,
                count_3dinh, count_5dinh,
                soNgayCachDinhDuong = 0, chechlechDuong = 0,
                countMAX;
            float valMaxDuong;
            List<int> listResult = new List<int>();

            valMaxDuong = 0f;
            countMAX = 0;

            for (int soNgayCachDinh = 1; soNgayCachDinh < soNgayCachDinhMAX; soNgayCachDinh++)
                for (int chechlech = 1; chechlech < chechlechMAX; chechlech++)
                {
                    count_3dinh = 0;
                    count_5dinh = 0;
                    foreach (List<float> listVal in listDuong)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlech / 100f);
                        if (sodinh > 0)
                        {
                            if (sodinh <= soDinhCheck)
                                count_3dinh++;
                            if (sodinh <= soDinhMAX)
                                count_5dinh++;
                        }
                    }
                    if (soNgayCachDinh == 1 && chechlech == 1)
                        soSongDuong = count_5dinh;

                    if (count_3dinh > countMAX)
                    {
                        countMAX = count_3dinh;
                        valMaxDuong = (float)count_3dinh / soSongDuong;
                        soNgayCachDinhDuong = soNgayCachDinh;
                        chechlechDuong = chechlech;
                    }
                }
            listResult.Add(soNgayCachDinhDuong);
            listResult.Add(chechlechDuong);

            valMaxDuong = 0f;
            countMAX = 0;

            for (int soNgayCachDinh = 1; soNgayCachDinh < soNgayCachDinhMAX; soNgayCachDinh++)
                for (int chechlech = 1; chechlech < chechlechMAX; chechlech++)
                {
                    count_3dinh = 0;
                    count_5dinh = 0;
                    foreach (List<float> listVal in listAm)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlech / 100f);
                        if (sodinh > 0)
                        {
                            if (sodinh <= soDinhCheck)
                                count_3dinh++;
                            if (sodinh <= soDinhMAX)
                                count_5dinh++;
                        }
                    }
                    if (soNgayCachDinh == 1 && chechlech == 1)
                        soSongAm = count_5dinh;

                    if (count_3dinh > countMAX)
                    {
                        countMAX = count_3dinh;
                        valMaxDuong = (float)count_3dinh / soSongAm;
                        soNgayCachDinhDuong = soNgayCachDinh;
                        chechlechDuong = chechlech;
                    }
                }
            listResult.Add(soNgayCachDinhDuong);
            listResult.Add(chechlechDuong);
            #endregion

            return listResult;
        }

        public static List<int> Testing_BackTest_HistorgramMACD_Statistic_Chechlech_SoNgay(List<List<float>> listSongDuong, List<List<float>> listSongAm, int soDinhMAX, int soDinhCheck)
        {
            /// Return list 2 giá trị: 
            /// [0], [1], [2] = max phần sóng dương (số ngày - chêch lệch - phần trăm chính xác)
            /// [3], [4], [5] = max phần sóng âm    (số ngày - chêch lệch - phần trăm chính xác)
            
            #region Thống kê
            int sodinh,
                soNgayCachDinhMAX = 5,
                chechlechMAX = 30,
                soSongDuong = 100000,
                soSongAm = 100000,
                count_3dinh, count_5dinh,
                soNgayCachDinhDuong = 0, chechlechDuong = 0,
                countMAX;
            float valMaxDuong;
            List<int> listResult = new List<int>();

            valMaxDuong = 0f;
            countMAX = 0;

            for (int soNgayCachDinh = 1; soNgayCachDinh < soNgayCachDinhMAX; soNgayCachDinh++)
                for (int chechlech = 1; chechlech < chechlechMAX; chechlech++)
                {
                    count_3dinh = 0;
                    count_5dinh = 0;
                    foreach (List<float> listVal in listSongDuong)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlech / 100f);
                        if (sodinh > 0)
                        {
                            if (sodinh <= soDinhCheck)
                                count_3dinh++;
                            if (sodinh <= soDinhMAX)
                                count_5dinh++;
                        }
                    }
                    if (soNgayCachDinh == 1 && chechlech == 1)
                        soSongDuong = count_5dinh;

                    if (count_3dinh > countMAX)
                    {
                        countMAX = count_3dinh;
                        valMaxDuong = (float)count_3dinh / soSongDuong;
                        soNgayCachDinhDuong = soNgayCachDinh;
                        chechlechDuong = chechlech;
                    }
                }
            listResult.Add(soNgayCachDinhDuong);
            listResult.Add(chechlechDuong);
            listResult.Add((int)(valMaxDuong * 100));

            valMaxDuong = 0f;
            countMAX = 0;
            for (int soNgayCachDinh = 1; soNgayCachDinh < soNgayCachDinhMAX; soNgayCachDinh++)
                for (int chechlech = 1; chechlech < chechlechMAX; chechlech++)
                {
                    count_3dinh = 0;
                    count_5dinh = 0;
                    foreach (List<float> listVal in listSongAm)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlech / 100f);
                        if (sodinh > 0)
                        {
                            if (sodinh <= soDinhCheck)
                                count_3dinh++;
                            if (sodinh <= soDinhMAX)
                                count_5dinh++;
                        }
                    }
                    if (soNgayCachDinh == 1 && chechlech == 1)
                        soSongAm = count_5dinh;

                    if (count_3dinh > countMAX)
                    {
                        countMAX = count_3dinh;
                        valMaxDuong = (float)count_3dinh / soSongAm;
                        soNgayCachDinhDuong = soNgayCachDinh;
                        chechlechDuong = chechlech;
                    }
                }
            listResult.Add(soNgayCachDinhDuong);
            listResult.Add(chechlechDuong);
            listResult.Add((int)(valMaxDuong * 100));
            #endregion

            return listResult;
        }

        public static void Testing_BackTest_HistorgramMACD_Statistic_MauDuLieu()
        {
            /// Return list 2 giá trị: 
            /// [0], [1], [2] = max phần sóng dương (số ngày - chêch lệch - phần trăm chính xác)
            /// [3], [4], [5] = max phần sóng âm    (số ngày - chêch lệch - phần trăm chính xác)

            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();
            List<float> listValues_TK = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;

            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh,
                soNgayCachDinh = 2,
                countSong = 0
                ;
            Random ran = new Random();

            List<int> listResult = new List<int>();
            int[] chechlechArray = new int[] { 8, 18 };
            float[] percentMauArray = new float[] { 0.1f, 0.2f, 0.4f, 0.6f, 0.8f, 1f };
            List<int> listCount = new List<int>();
            listFile = new List<string>();
            foreach (float percentMau in percentMauArray)
            {
                countSong = 0;
                listCount = new List<int>();
                for (int i = 0; i < chechlechArray.Length; i++)
                    listCount.Add(0);
                foreach (List<float> listVal in listDuong)
                {
                    if (ran.NextDouble() > percentMau)
                        continue;
                    else
                        countSong++;

                    for (int j = 0; j < chechlechArray.Length; j++)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlechArray[j] / 100f);
                        if (sodinh > 0 && sodinh <= 1)
                            listCount[j]++;
                    }
                }

                for (int i = 0; i < chechlechArray.Length; i++)
                    listFile.Add("DUONG -- %Mau: " + percentMau + "\tSo ngay: " + soNgayCachDinh + "\t Chech lech: " + chechlechArray[i]
                        + "\t Do chinh xac: " + Math.Round((float)listCount[i] / countSong, 3));
            }
            listFile.Add("\t\t");
            foreach (float percentMau in percentMauArray)
            {
                countSong = 0;
                listCount = new List<int>();
                for (int i = 0; i < chechlechArray.Length; i++)
                    listCount.Add(0);
                foreach (List<float> listVal in listAm)
                {
                    if (ran.NextDouble() > percentMau)
                        continue;
                    else
                        countSong++;

                    for (int j = 0; j < chechlechArray.Length; j++)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, chechlechArray[j] / 100f);
                        if (sodinh > 0 && sodinh <= 1)
                            listCount[j]++;
                    }
                }

                for (int i = 0; i < chechlechArray.Length; i++)
                    listFile.Add("AM    -- %Mau: " + percentMau + "\tSo ngay: " + soNgayCachDinh + "\t Chech lech: " + chechlechArray[i]
                        + "\t Do chinh xac: " + Math.Round((float)listCount[i] / countSong, 3));
            }

            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD_Statistic_MauDuLieu.txt", listFile);
            #endregion

        }

        public static void Testing_BackTest_HistorgramMACD_XacDinh_SoDinh()
        {
            /// Return list 2 giá trị: 
            /// [0], [1], [2] = max phần sóng dương (số ngày - chêch lệch - phần trăm chính xác)
            /// [3], [4], [5] = max phần sóng âm    (số ngày - chêch lệch - phần trăm chính xác)

            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();
            List<float> listValues_TK = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;

            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 5)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Thống kê
            int sodinh,
                soNgayCachDinh = 2, soDinhCheck = 1,
                countSong , countMAX,
                countTemp
                ;
            float chinhxac = 0;
            Random ran = new Random();
            string row = "";
            List<int> listResult = new List<int>(); 
            List<int> listCount = new List<int>();
            List<float> listPercent = new List<float>();
            List<float> listPercentResult = new List<float>();

            #region Sóng dương
            listFile = new List<string>();
            countSong = listDuong.Count;
            countMAX = 0;
            for(int i = 1; i < 50; i = i + 1)
                for (int j = 1; j < 50; j = j + 1)
                {
                    listPercent = new List<float>();
                    listPercent.Add(i / 100f);
                    listPercent.Add(j / 100f);
                    countTemp = 0;

                    foreach (List<float> listVal in listDuong)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, listPercent);
                        if (sodinh > 0 && sodinh <= soDinhCheck)
                            countTemp++;
                    }

                    if (countTemp > countMAX)
                    {
                        countMAX = countTemp;
                        listPercentResult = new List<float>(listPercent);
                        chinhxac = (float)countTemp / countSong;
                        chinhxac = (float) Math.Round(chinhxac, 2);
                    }
                }
            
            foreach (float v in listPercentResult)
                row += (float)Math.Round(v, 2) + "  ";
            listFile.Add("DUONG: So Ngay: " + soNgayCachDinh + "\tTi le Dinh: " + row
                + "\t Chinh xac: " + chinhxac);
            #endregion

            #region Sóng âm          
            countSong = listAm.Count;
            countMAX = 0;
            for (int i = 1; i < 50; i = i + 1)
                for (int j = 1; j < 50; j = j + 1)
                {
                    listPercent = new List<float>();
                    listPercent.Add(i / 100f);
                    listPercent.Add(j / 100f);
                    countTemp = 0;

                    foreach (List<float> listVal in listAm)
                    {
                        sodinh = 0;
                        sodinh = CoreFunctions.Tk_SoDinh1Song_HistogramMACD(listVal, soNgayCachDinh, listPercent);
                        if (sodinh > 0 && sodinh <= soDinhCheck)
                            countTemp++;
                    }

                    if (countTemp > countMAX)
                    {
                        countMAX = countTemp;
                        listPercentResult = new List<float>(listPercent);
                        chinhxac = (float)countTemp / countSong;
                        chinhxac = (float)Math.Round(chinhxac, 2);
                    }
                }
            row = "";
            foreach (float v in listPercentResult)
                row += (float)Math.Round(v, 2) + "  ";
            listFile.Add("AM   : So Ngay: " + soNgayCachDinh + "\tTi le Dinh: " + row
                + "\t Chinh xac: " + chinhxac);
            #endregion

            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD_XacDinh_SoDinh.txt", listFile);
            #endregion

        }

        public static void Testing_BackTest_HistorgramMACD_DieuChinh()
        {
            #region Biến và load dữ liệu
            List<string> listFile = new List<string>();
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistogramMACD.txt");

            List<List<float>> listDuong = new List<List<float>>();
            List<List<float>> listAm = new List<List<float>>();
            List<float> listValues = new List<float>();

            bool flag_am = false, flag_break = false;
            float val;
            List<float> listValues_TK = new List<float>();
            foreach (string str in listFile)
            {
                string[] part = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 10)
                {
                    flag_am = false; flag_break = false;
                    listValues = new List<float>();
                    foreach (string s in part)
                    {
                        val = float.Parse(s);
                        if (val < 0)
                            flag_am = true;
                        val = Math.Abs(val);
                        listValues_TK.Add(val);

                        if (val < 0)
                        {
                            listValues = new List<float>();
                            flag_break = true;
                            break;
                        }
                        else
                            listValues.Add(val);
                    }

                    if (flag_break == false && listValues.Count > 0)
                    {
                        if (flag_am)
                            listAm.Add(new List<float>(listValues));
                        else
                            listDuong.Add(new List<float>(listValues));
                    }
                    else
                        continue;
                }
            }
            #endregion

            #region Điều chỉnh dữ liệu
            float percentChechLech = 0.05f;
            List<float> listVal = new List<float>();
            listFile = new List<string>();
            string row = "";

            #region list Dương
            for (int i = 0; i < listDuong.Count; i++)
            {
                listVal = listDuong[i];
                row = "";

                for (int j = listVal.Count - 1; j > 0; j--)
                    if (Math.Abs(Math.Log(listVal[j] / listVal[j - 1])) <= percentChechLech)
                    {
                        listVal[j - 1] = (listVal[j] + listVal[j - 1]) / 2;
                        listVal.RemoveAt(j);
                    }

                foreach (float value in listVal)
                    row += Math.Round(value, 3) + "  ";
                listFile.Add(row);
            }
            #endregion

            #region list Âm
            for (int i = 0; i < listAm.Count; i++)
            {
                listVal = listAm[i];
                row = "";

                for (int j = 0; j < listVal.Count - 1; j++)
                    if (Math.Log(listVal[j] / listVal[j + 1]) <= percentChechLech)
                    {
                        listVal[j] = (listVal[j] + listVal[j + 1]) / 2 * (-1f);
                        listVal.RemoveAt(j + 1);
                        j--;
                    }
                foreach (float value in listVal)
                    row += Math.Round(value, 3) + "  ";
                listFile.Add(row);
            }
            #endregion
            #endregion

            #region Ghi File
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_HistorgramMACD_DieuChinh.txt", listFile);
            #endregion
        }

        public static void Testing_BackTest_ADLine()
        {
            List<float> listAD = new List<float>();
            List<string> listResult = new List<string>();
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
            {
                listAD = new List<float>();
                listAD = Indicators.AccumulationDistributionLine(cp.DanhSachGiaMoCua, cp.DanhSachGiaDongCua
                                        , cp.DanhSachGiaCaoNhat, cp.DanhSachGiaThapNhat, cp.DanhSachKhoiLuongGiaoDich);
                if (listAD.Count == cp.DanhSachNgayGiaoDich_String.Count)                
                    for (int i = 0; i < listAD.Count; i++)                    
                        listResult.Add(cp.TenCoPhieu + "\t" + cp.DanhSachNgayGiaoDich_String[i] + "\t" + listAD[i]);                
            }

            if (listResult.Count > 0)            
                CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\BackTest_ADLine.txt"
                                                , listResult);
            
        }

        public static void Testing_BackTest_MACD_Zscore()
        {
            #region *** Biến
            List<CoPhieu> DanhSachCoPhieu = ShareData.danhsachCoPhieu.DanhSachCoPhieu_List;

            List<int> portfilio = new List<int>();
            List<int> portfilio_now = new List<int>();
            List<int> id_dateBuy = new List<int>();
            List<int> id_dateSell = new List<int>();
            List<float> cumulative = new List<float>();
            List<float> priceBuy = new List<float>();
            List<float> priceSell = new List<float>();

            List<int> listTopIndex_Zscore = new List<int>();
            List<float> priceOfStock = new List<float>();
            List<float> MACD = new List<float>();
            List<float> signal = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuy = new List<float>();

            int time_shapre = 200;
            #endregion

            #region *** Điều chỉnh giá
            List<string> listDate = new List<string>();
            List<float> priceOfVNINDEX = new List<float>();

            /// Lấy danh sách ngày giao dịch và giá đóng cửa của VNINDEX
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listDate = cp.DanhSachNgayGiaoDich_String;
                    priceOfVNINDEX = cp.DanhSachGiaDongCua;
                    break;
                }

            listTopIndex_Zscore = new List<int>();
            for (int j = 0; j < ShareData.danhsachCoPhieu.DanhSachTenCoPhieu.Count; j++)
                if (ShareData.danhsachCoPhieu.DanhSachTenCoPhieu[j] != "^VNINDEX"
                    || listDate[0] == ShareData.danhsachCoPhieu.DanhSachCoPhieu_List[j].DanhSachNgayGiaoDich_String[0])
                    listTopIndex_Zscore.Add(j);

            List<List<float>> listPriceOfStock = new List<List<float>>();
            foreach (int index in listTopIndex_Zscore)
            {
                priceOfStock = new List<float>();
                /// Lấy giá CP có thời gian tương ứng
                for (int j = 0; j < DanhSachCoPhieu[index].DanhSachGiaDongCua.Count; j++)
                    priceOfStock.Add(DanhSachCoPhieu[index].DanhSachGiaDongCua[j]);

                /// Điều chỉnh giá cổ phiếu (tránh tình trạng bị thưởng cổ tức)
                List<float> listTemp = new List<float>();
                float temp;
                for (int j = priceOfStock.Count - 1; j > 0; j--)
                {
                    temp = (priceOfStock[j - 1] - priceOfStock[j]) / priceOfStock[j];
                    if (temp < -0.07f)
                        temp = 0;
                    listTemp.Add(temp);
                }
                temp = priceOfStock[priceOfStock.Count - 1];
                priceOfStock = new List<float>();
                priceOfStock.Add(temp);

                foreach (float f in listTemp)
                {
                    temp = temp * (1 + f);
                    priceOfStock.Insert(0, temp);
                }
                listPriceOfStock.Add(priceOfStock);
            }

            #endregion

            for (int i = time_shapre; i > 3; i--)
            {
                listTopIndex_Zscore = ShareData.danhsachCoPhieu.Xuly_LayIndexTopNZScore(3, i);

                #region *** Find Securities for Buying
                foreach (int index in listTopIndex_Zscore)
                    if (portfilio_now.Contains(index) == false)
                    {
                        priceOfStock = new List<float>();

                        /// Lấy giá CP có thời gian tương ứng
                        for (int j = i; j < listPriceOfStock[index].Count; j++)
                            priceOfStock.Add(listPriceOfStock[index][j]);

                        /// Tính Histogram MACD
                        MACD = new List<float>();
                        signal = new List<float>();
                        histogram = new List<float>();
                        Indicators.MACD(priceOfStock, 12, 26, 9, ref MACD, ref signal);
                        for (int j = 0; j < signal.Count && j < 30; j++)
                            histogram.Add(MACD[j] - signal[j]);

                        /// Tính Signal BuySell
                        listSignalBuy = Indicators.GetSignalBuySell(histogram);

                        /// Cập nhật danh mục (tín hiệu cách 2 ngày
                        for (int j = 0; j < 1; j++)
                            if (listSignalBuy[j] > 0) // có tín hiệu mua vào
                            {
                                portfilio_now.Add(index);
                                portfilio.Add(index);
                                id_dateBuy.Add(i);
                                id_dateSell.Add(-1000); /// Add vào trước để cập nhật sau này dễ hơn
                                priceBuy.Add(priceOfStock[0]);
                                priceSell.Add(-1000);
                                break;
                            }
                    }
                #endregion

                #region *** Checking Selling for Portfilio
                for (int k = 0; k < portfilio_now.Count; k++)
                {
                    priceOfStock = new List<float>();

                    /// Lấy giá CP có thời gian tương ứng
                    for (int j = i; j < listPriceOfStock[portfilio_now[k]].Count; j++)
                        priceOfStock.Add(listPriceOfStock[portfilio_now[k]][j]);

                    /// Tính Histogram MACD
                    MACD = new List<float>();
                    signal = new List<float>();
                    histogram = new List<float>();
                    Indicators.MACD(priceOfStock, 12, 26, 9, ref MACD, ref signal);
                    for (int j = 0; j < signal.Count && j < 20; j++)
                        histogram.Add(MACD[j] - signal[j]);

                    /// Tính Signal BuySell
                    listSignalBuy = Indicators.GetSignalBuySell(histogram);

                    for (int f = 0; f < portfilio.Count; f++)
                        if (portfilio[f] == portfilio_now[k] && id_dateSell[f] == -1000)
                        {
                            if (
                                listSignalBuy[0] < 0 || listSignalBuy[1] < 0 || /// có tín hiệu mua
                                (priceOfStock[0] / priceBuy[f] - 1) >= 0.08 || /// lợi nhuận đạt 8%  
                                id_dateBuy[f] - i >= 12                       /// nắm giữ cổ được 12 ngày
                                //((priceOfStock[0] / priceBuy[f] - 1) < -0.05 &&  id_dateBuy[f] - i >= 4)  /// lỗ 2% và nắm cổ được 4 ngày
                                //histogram[0] > 0 || histogram[1] > 0 
                                )
                            {
                                id_dateSell[f] = i;
                                priceSell[f] = priceOfStock[0];
                                portfilio_now.RemoveAt(k);
                                k--;
                                break;
                            }
                        }
                }
                #endregion
            }

            #region *** Ghi ra file

            List<string> listContent = new List<string>();
            List<float> dailyReturn_VNINDEX = new List<float>();
            for (int i = 0; i < priceBuy.Count; i++)
            {
                if (priceSell[i] == -1000)
                {
                    priceSell[i] = DanhSachCoPhieu[portfilio[i]].DanhSachGiaDongCua[0];
                    id_dateSell[i] = 0;
                }
                cumulative.Add(priceSell[i] / priceBuy[i] - 1);
                dailyReturn_VNINDEX.Add(priceOfVNINDEX[id_dateSell[i]] / priceOfVNINDEX[id_dateBuy[i]] - 1);
            }

            /// Tính Sharpe của toàn bộ VNINDEX từ bắt đầu danh mục đến kết thúc danh mục
            List<float> priceOfVNINDEX_mini = new List<float>();
            for (int i = id_dateSell[id_dateSell.Count - 1]; i <= id_dateBuy[0]; i++)
                priceOfVNINDEX_mini.Add(priceOfVNINDEX[i]);
            List<float> dailyReturn_VNINDEX_mini = CoreFunctions.Tk_GetDailyReturn(priceOfVNINDEX_mini);

            /// Thông tin cần in ra
            listContent.Add("Average Portfilio: " + Math.Round(CoreFunctions.Tk_GetAverage(cumulative), 4));
            listContent.Add("Std     Portfilio: " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(cumulative), 4));
            listContent.Add("Sharpe  Portfilio: " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(cumulative) / CoreFunctions.Tk_PopularStandardDeviation(cumulative), 4));

            listContent.Add("");
            listContent.Add("Average VNINDEX:   " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX_mini), 4));
            listContent.Add("Std     VNINDEX:   " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX_mini), 4));
            listContent.Add("Sharpe  VNINDEX:   " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX_mini) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX_mini), 4));

            listContent.Add("");
            listContent.Add("Average HSXStep:   " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX), 4));
            listContent.Add("Std     HSXStep:   " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX), 4));
            listContent.Add("Sharpe  HSXStep:   " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX), 4));
            listContent.Add("");

            listContent.Add("");
            listContent.Add("CP\tDateBuy\tDateSell\tPriceBuy\tPriceSell\tReturn\tReturnVNINDEX");
            listContent.Add("--------------------------------------------------------");
            for (int i = 0; i < priceBuy.Count; i++)
            {
                listContent.Add(
                    DanhSachCoPhieu[portfilio[i]].TenCoPhieu + "\t" +
                    listDate[id_dateBuy[i]] + "(" + id_dateBuy[i] + ")" + "\t" +
                    listDate[id_dateSell[i]] + "(" + id_dateSell[i] + ")" + "\t" +
                    Math.Round(priceBuy[i], 1) + "\t" +
                    Math.Round(priceSell[i], 1).ToString() + "\t" +
                    Math.Round(cumulative[i], 4).ToString() + "\t" +
                    Math.Round(priceOfVNINDEX[id_dateSell[i]] / priceOfVNINDEX[id_dateBuy[i]] - 1, 4).ToString()
                    );
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_MACD_Zscore.txt", listContent);
            #endregion
        }

        public static void Testing_BackTest_MACD()
        {
            #region *** Biến
            List<CoPhieu> DanhSachCoPhieu = ShareData.danhsachCoPhieu.DanhSachCoPhieu_List;

            List<int> portfilio = new List<int>();
            List<int> portfilio_now = new List<int>();
            List<int> id_dateBuy = new List<int>();
            List<int> id_dateSell = new List<int>();
            List<float> cumulative = new List<float>();
            List<float> priceBuy = new List<float>();
            List<float> priceSell = new List<float>();

            List<int> listTopIndex_Zscore = new List<int>();
            List<float> priceOfStock = new List<float>();
            List<float> MACD = new List<float>();
            List<float> signal = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuy = new List<float>();

            int time_shapre = 200;
            #endregion

            #region *** Điều chỉnh giá
            List<string> listDate = new List<string>();
            List<float> priceOfVNINDEX = new List<float>();

            /// Lấy danh sách ngày giao dịch và giá đóng cửa của VNINDEX
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listDate = cp.DanhSachNgayGiaoDich_String;
                    priceOfVNINDEX = cp.DanhSachGiaDongCua;
                    break;
                }

            listTopIndex_Zscore = new List<int>();
            for (int j = 0; j < ShareData.danhsachCoPhieu.DanhSachTenCoPhieu.Count; j++)
                if (ShareData.danhsachCoPhieu.DanhSachTenCoPhieu[j] != "^VNINDEX"
                   || listDate[0] == ShareData.danhsachCoPhieu.DanhSachCoPhieu_List[j].DanhSachNgayGiaoDich_String[0])
                    listTopIndex_Zscore.Add(j);

            List<List<float>> listPriceOfStock = new List<List<float>>();
            foreach (int index in listTopIndex_Zscore)
            {
                priceOfStock = new List<float>();

                /// Lấy giá CP có thời gian tương ứng
                for (int j = 0; j < DanhSachCoPhieu[index].DanhSachGiaDongCua.Count; j++)
                    priceOfStock.Add(DanhSachCoPhieu[index].DanhSachGiaDongCua[j]);

                /// Điều chỉnh giá cổ phiếu (tránh tình trạng bị thưởng cổ tức)
                List<float> listTemp = new List<float>();
                float temp;
                for (int j = priceOfStock.Count - 1; j > 0; j--)
                {
                    temp = (priceOfStock[j - 1] - priceOfStock[j]) / priceOfStock[j];
                    if (temp < -0.07f)
                        temp = 0;
                    listTemp.Add(temp);
                }
                temp = priceOfStock[priceOfStock.Count - 1];
                priceOfStock = new List<float>();
                priceOfStock.Add(temp);

                foreach (float f in listTemp)
                {
                    temp = temp * (1 + f);
                    priceOfStock.Insert(0, temp);
                }
                listPriceOfStock.Add(priceOfStock);
            }
            #endregion

            for (int i = time_shapre; i > 3; i--)
            {
                #region *** Find Securities for Buying
                foreach (int index in listTopIndex_Zscore)
                    if (portfilio_now.Contains(index) == false)
                    {
                        priceOfStock = new List<float>();
                        /// Lấy giá CP có thời gian tương ứng
                        for (int j = i; j < listPriceOfStock[index].Count; j++)
                            priceOfStock.Add(listPriceOfStock[index][j]);

                        /// Tính Histogram MACD
                        MACD = new List<float>();
                        signal = new List<float>();
                        histogram = new List<float>();
                        Indicators.MACD(priceOfStock, 12, 26, 9, ref MACD, ref signal);
                        for (int j = 0; j < signal.Count && j < 30; j++)
                            histogram.Add(MACD[j] - signal[j]);

                        /// Tính Signal BuySell
                        listSignalBuy = Indicators.GetSignalBuySell(histogram);

                        /// Cập nhật danh mục (tín hiệu cách 2 ngày
                        for (int j = 0; j < 1; j++)
                            if (listSignalBuy[j] > 0 && DanhSachCoPhieu[index].DanhSachGiaDongCua[i] > 7f) // có tín hiệu mua vào
                            {
                                portfilio_now.Add(index);
                                portfilio.Add(index);
                                id_dateBuy.Add(i);
                                id_dateSell.Add(-1000); /// Add vào trước để cập nhật sau này dễ hơn
                                priceBuy.Add(priceOfStock[0]);
                                priceSell.Add(-1000);
                                break;
                            }
                    }
                #endregion

                #region *** Checking Selling for Portfilio
                for (int k = 0; k < portfilio_now.Count; k++)
                {
                    priceOfStock = new List<float>();

                    /// Lấy giá CP có thời gian tương ứng
                    for (int j = i; j < listPriceOfStock[portfilio_now[k]].Count; j++)
                        priceOfStock.Add(listPriceOfStock[portfilio_now[k]][j]);

                    /// Tính Histogram MACD
                    MACD = new List<float>();
                    signal = new List<float>();
                    histogram = new List<float>();
                    Indicators.MACD(priceOfStock, 12, 26, 9, ref MACD, ref signal);
                    for (int j = 0; j < signal.Count && j < 20; j++)
                        histogram.Add(MACD[j] - signal[j]);

                    /// Tính Signal BuySell
                    listSignalBuy = Indicators.GetSignalBuySell(histogram);

                    for (int f = 0; f < portfilio.Count; f++)
                        if (portfilio[f] == portfilio_now[k] && id_dateSell[f] == -1000)
                        {
                            if (
                                listSignalBuy[0] < 0 || listSignalBuy[1] < 0 || /// có tín hiệu mua
                                (priceOfStock[0] / priceBuy[f] - 1) >= 0.09 || /// lợi nhuận đạt 8%  
                                id_dateBuy[f] - i >= 12                       /// nắm giữ cổ được 12 ngày
                                //((priceOfStock[0] / priceBuy[f] - 1) < -0.07 &&  id_dateBuy[f] - i >= 4)  /// lỗ 2% và nắm cổ được 4 ngày
                                //histogram[0] > 0 || histogram[1] > 0 
                                )
                            {
                                id_dateSell[f] = i;
                                priceSell[f] = priceOfStock[0];
                                portfilio_now.RemoveAt(k);
                                k--;
                                break;
                            }
                        }
                }
                #endregion
            }

            #region *** Ghi ra file

            List<string> listContent = new List<string>();
            List<float> dailyReturn_VNINDEX = new List<float>();
            for (int i = 0; i < priceBuy.Count; i++)
            {
                if (priceSell[i] == -1000)
                {
                    priceSell[i] = DanhSachCoPhieu[portfilio[i]].DanhSachGiaDongCua[0];
                    id_dateSell[i] = 0;
                }
                cumulative.Add(priceSell[i] / priceBuy[i] - 1);
                dailyReturn_VNINDEX.Add(priceOfVNINDEX[id_dateSell[i]] / priceOfVNINDEX[id_dateBuy[i]] - 1);
            }

            /// Tính Sharpe của toàn bộ VNINDEX từ bắt đầu danh mục đến kết thúc danh mục
            List<float> priceOfVNINDEX_mini = new List<float>();
            for (int i = id_dateSell[id_dateSell.Count - 1]; i <= id_dateBuy[0]; i++)
                priceOfVNINDEX_mini.Add(priceOfVNINDEX[i]);
            List<float> dailyReturn_VNINDEX_mini = CoreFunctions.Tk_GetDailyReturn(priceOfVNINDEX_mini);

            /// Thông tin cần in ra
            listContent.Add("Average Portfilio: " + Math.Round(CoreFunctions.Tk_GetAverage(cumulative), 4));
            listContent.Add("Std     Portfilio: " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(cumulative), 4));
            listContent.Add("Sharpe  Portfilio: " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(cumulative) / CoreFunctions.Tk_PopularStandardDeviation(cumulative), 4));

            listContent.Add("");
            listContent.Add("Average VNINDEX:   " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX_mini), 4));
            listContent.Add("Std     VNINDEX:   " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX_mini), 4));
            listContent.Add("Sharpe  VNINDEX:   " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX_mini) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX_mini), 4));

            listContent.Add("");
            listContent.Add("Average HSXStep:   " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX), 4));
            listContent.Add("Std     HSXStep:   " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX), 4));
            listContent.Add("Sharpe  HSXStep:   " + Math.Round(Math.Sqrt(time_shapre)
                * CoreFunctions.Tk_GetAverage(dailyReturn_VNINDEX) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn_VNINDEX), 4));
            listContent.Add("");

            listContent.Add("");
            listContent.Add("CP\tDateBuy\tDateSell\tPriceBuy\tPriceSell\tReturn\tReturnVNINDEX");
            listContent.Add("--------------------------------------------------------");
            for (int i = 0; i < priceBuy.Count; i++)
            {
                listContent.Add(
                    DanhSachCoPhieu[portfilio[i]].TenCoPhieu + "\t" +
                    listDate[id_dateBuy[i]] + "(" + id_dateBuy[i] + ")" + "\t" +
                    listDate[id_dateSell[i]] + "(" + id_dateSell[i] + ")" + "\t" +
                    Math.Round(priceBuy[i], 1) + "\t" +
                    Math.Round(priceSell[i], 1).ToString() + "\t" +
                    Math.Round(cumulative[i], 4).ToString() + "\t" +
                    Math.Round(priceOfVNINDEX[id_dateSell[i]] / priceOfVNINDEX[id_dateBuy[i]] - 1, 4).ToString()
                    );
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_MACD.txt", listContent);
            #endregion
        }

        public static void Testing_BackTest_VNINDEX_MACD()
        {
            List<string> listDate = new List<string>();
            List<float> priceOfVNINDEX = new List<float>();

            /// Lấy danh sách ngày giao dịch và giá đóng cửa của VNINDEX
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listDate = cp.DanhSachNgayGiaoDich_String;
                    for (int i = 0; i < cp.DanhSachGiaDongCua.Count && i < 1000; i++)
                        priceOfVNINDEX.Add(cp.DanhSachGiaDongCua[i]);
                    break;
                }

            List<float> MACD = new List<float>();
            List<float> signal = new List<float>();
            List<float> histogram = new List<float>();
            Indicators.MACD(priceOfVNINDEX, 12, 26, 9, ref MACD, ref signal);
            for (int j = 0; j < signal.Count; j++)
                histogram.Add(MACD[j] - signal[j]);

            /// Tính Signal BuySell
            List<float> listSignalBuySell = Indicators.GetSignalBuySell(histogram);

            List<float> dailyReturn = new List<float>();

            string dateBuy = "";
            float priceBuy = 0f, priceSell = 0f;
            int id_buy = 0;
            List<string> listContent = new List<string>();

            listContent.Add("");
            listContent.Add("DateBuy\tDateSell\tPriceBuy\tPriceSell\tReturn");
            listContent.Add("------------------------------------------------");
            for (int i = listSignalBuySell.Count - 1; i >= 0; i--)
            {
                if (listSignalBuySell[i] > 0 && dateBuy == "") /// Có tín hiệu mua
                {
                    dateBuy = listDate[i] + "(" + i.ToString() + ")";
                    priceBuy = priceOfVNINDEX[i];
                    id_buy = i;
                }
                else if (dateBuy != "" &&
                          (listSignalBuySell[i] < 0
                             || id_buy - i >= 5 && (priceOfVNINDEX[i] / priceBuy - 1) < -0.03f
                          )
                        ) /// Có tín hiệu bán
                {
                    dateBuy += "\t" + listDate[i] + "(" + i.ToString() + ")";
                    priceSell = priceOfVNINDEX[i];
                    dailyReturn.Insert(0, priceSell / priceBuy - 1);
                    listContent.Add(dateBuy + "\t" + priceBuy + "\t" + priceSell
                        + "\t" + Math.Round(dailyReturn[0] * 100, 2));
                    dateBuy = "";
                }
            }

            listContent.Insert(0, "Average: " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn), 4));
            listContent.Insert(0, "Std:     " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn), 4));
            listContent.Insert(0, "Sharpe:  " + Math.Round(Math.Sqrt(priceOfVNINDEX.Count)
                * CoreFunctions.Tk_GetAverage(dailyReturn) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn), 4));
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_VNINDEX_MACD.txt", listContent);
        }

        public static void Testing_BackTest_Stock_MACD(string nameStock)
        {
            List<string> listDate = new List<string>();
            List<float> priceOfStock = new List<float>();

            /// Lấy danh sách ngày giao dịch và giá đóng cửa của VNINDEX
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == nameStock.ToUpper())
                {
                    listDate = cp.DanhSachNgayGiaoDich_String;
                    for (int i = 0; i < cp.DanhSachGiaDongCua.Count && i < 1000; i++)
                        priceOfStock.Add(cp.DanhSachGiaDongCua[i]);
                    break;
                }

            /// Điều chỉnh giá cổ phiếu (tránh tình trạng bị thưởng cổ tức)
            List<float> listTemp = new List<float>();
            float temp;
            for (int j = priceOfStock.Count - 1; j > 0; j--)
            {
                temp = (priceOfStock[j - 1] - priceOfStock[j]) / priceOfStock[j];
                if (temp < -0.07f)
                    temp = 0;
                listTemp.Add(temp);
            }
            temp = priceOfStock[priceOfStock.Count - 1];
            priceOfStock = new List<float>();
            priceOfStock.Add(temp);

            foreach (float f in listTemp)
            {
                temp = temp * (1 + f);
                priceOfStock.Insert(0, temp);
            }

            List<float> MACD = new List<float>();
            List<float> signal = new List<float>();
            List<float> histogram = new List<float>();
            Indicators.MACD(priceOfStock, 12, 26, 9, ref MACD, ref signal);
            for (int j = 0; j < signal.Count; j++)
                histogram.Add(MACD[j] - signal[j]);

            /// Tính Signal BuySell
            List<float> listSignalBuySell = Indicators.GetSignalBuySell(histogram);

            List<float> dailyReturn = new List<float>();

            string dateBuy = "";
            float priceBuy = 0f, priceSell = 0f;
            int id_buy = 0;
            List<string> listContent = new List<string>();

            listContent.Add("");
            listContent.Add("DateBuy\tDateSell\tPriceBuy\tPriceSell\tReturn");
            listContent.Add("------------------------------------------------");
            for (int i = listSignalBuySell.Count - 1; i >= 0; i--)
            {
                if (listSignalBuySell[i] > 0 && dateBuy == "") /// Có tín hiệu mua
                {
                    dateBuy = listDate[i] + "(" + i.ToString() + ")";
                    priceBuy = priceOfStock[i];
                    id_buy = i;
                }
                else if (dateBuy != "" &&
                          (listSignalBuySell[i] < 0
                             || id_buy - i >= 5 && (priceOfStock[i] / priceBuy - 1) < -0.03f
                          )
                        ) /// Có tín hiệu bán
                {
                    dateBuy += "\t" + listDate[i] + "(" + i.ToString() + ")";
                    priceSell = priceOfStock[i];
                    dailyReturn.Insert(0, priceSell / priceBuy - 1);
                    listContent.Add(dateBuy + "\t" + priceBuy + "\t" + priceSell
                        + "\t" + Math.Round(dailyReturn[0] * 100, 2));
                    dateBuy = "";
                }
            }

            listContent.Insert(0, "Average: " + Math.Round(CoreFunctions.Tk_GetAverage(dailyReturn), 4));
            listContent.Insert(0, "Std:     " + Math.Round(CoreFunctions.Tk_PopularStandardDeviation(dailyReturn), 4));
            listContent.Insert(0, "Sharpe:  " + Math.Round(Math.Sqrt(priceOfStock.Count)
                * CoreFunctions.Tk_GetAverage(dailyReturn) / CoreFunctions.Tk_PopularStandardDeviation(dailyReturn), 4));
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_" + nameStock.ToUpper() + "_MACD.txt", listContent);
        }

        public static void Testing_BackTest_Stock_AVG_STD(int soNgay, ref List<float> listAvg, ref List<float> listStd)
        {
            List<float> listResult = new List<float>();
            List<string> listcontent = new List<string>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAvg\tStd");
            listcontent.Add("-----------------------");

            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date)
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Insert(0, (float)Math.Round(listTemp[i], 1));

                    List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listvalue);

                    avg = CoreFunctions.Tk_GetAverage(DailyReturns);
                    std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                    avg = (float)Math.Round(avg, 5);
                    std = (float)Math.Round(std, 5);

                    listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                    listAvg.Add(avg);
                    listStd.Add(std);
                }
                else /// những cổ phiếu bị lỗi - không có dữ liệu tương ứng với VNINDEX
                {
                    listcontent.Add(cp.TenCoPhieu + "\t" + -10000 + "\t" + -10000);
                    listAvg.Add(-10000);
                    listStd.Add(-10000);
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);
        }

        public static void Testing_BackTest_Stock_AVG_STD(int soNgay, List<string> listNameCP, ref List<float> listAvg, ref List<float> listStd)
        {
            List<float> listResult = new List<float>();
            List<string> listcontent = new List<string>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAvg\tStd");
            listcontent.Add("-----------------------");

            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date 
                    && (listNameCP.Contains(cp.TenCoPhieu) || cp.TenCoPhieu == "^VNINDEX"))
                {
                    if (listNameCP.Contains(cp.TenCoPhieu))
                        listNameCP.RemoveAt(listNameCP.IndexOf(cp.TenCoPhieu));

                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Insert(0, (float)Math.Round(listTemp[i], 1));

                    List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listvalue);

                    avg = CoreFunctions.Tk_GetAverage(DailyReturns);
                    std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                    avg = (float)Math.Round(avg, 5);
                    std = (float)Math.Round(std, 5);

                    if (cp.TenCoPhieu != "^VNINDEX")
                    {
                        listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                        listAvg.Add(avg);
                        listStd.Add(std);
                    }
                    else
                    {
                        listcontent.Insert(0, cp.TenCoPhieu + "\t" + avg + "\t" + std);
                        listAvg.Insert(0, avg);
                        listStd.Insert(0, std);
                    }
                }
                else /// những cổ phiếu bị lỗi - không có dữ liệu tương ứng với VNINDEX
                {
                    listcontent.Add(cp.TenCoPhieu + "\t" + -10000 + "\t" + -10000);
                    listAvg.Add(-10000);
                    listStd.Add(-10000);
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);
        }

        public static void Testing_BackTest_Stock_ConvexOptimation(int soNgay, ref List<float> listAvg, ref List<float> listStd)
        {
            List<float> listResult = new List<float>();
            List<string> listcontent = new List<string>();
            List<string> listStock = new List<string>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();
            List<List<float>> listPriceOfStock = new List<List<float>>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAVG\tSTD");
            listcontent.Add("-----------------------");
            int count = 0;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date)
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Add(listTemp[i]);
                    avg = CoreFunctions.Tk_GetAverage(CoreFunctions.Tk_GetDailyReturn(listvalue));

                    if (avg > 0 && count < 200 && cp.DanhSachGiaDongCua[0] > 7)
                    {
                        count++;
                        listPriceOfStock.Add(new List<float>());
                        foreach (float val in listvalue)
                            listPriceOfStock[listPriceOfStock.Count - 1].Add(val);

                        std = CoreFunctions.Tk_PopularStandardDeviation(CoreFunctions.Tk_GetDailyReturn(listvalue));

                        avg = (float)Math.Round(avg, 4);
                        std = (float)Math.Round(std, 4);

                        listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                        listAvg.Add(avg);
                        listStd.Add(std);
                        listStock.Add(cp.TenCoPhieu);
                    }
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);

            //// xây dựng ma trận pearson coeff, array mean(avg)và tên stock
            float[,] matrix = new float[listStock.Count, listStock.Count];
            float temp = 0f;
            for (int i = 0; i < listStock.Count; i++)
            {
                /// đường chéo chính
                matrix[i, i] = (float)Math.Pow(listStd[i], 2);
                for (int j = i + 1; j < listStock.Count; j++)
                {
                    temp = CoreFunctions.MR_TinhPearsonCorrelationCoefficient(listPriceOfStock[i], listPriceOfStock[j]);
                    matrix[i, j] = temp;
                    matrix[j, i] = temp;
                }
            }

            listcontent = new List<string>();
            string row = "";
            for (int i = 0; i < listStock.Count; i++)
            {
                row = "";
                for (int j = 0; j < listStock.Count; j++)
                    row += (float)Math.Round(matrix[i, j], 3) + ",";

                row = row.Substring(0, row.Length - 1);
                listcontent.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_MatrixPearsonCoeff.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            foreach (float val in listAvg)
                row += (float)Math.Round(val, 3) + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_ArrayMean.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            foreach (string name in listStock)
                row += name + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_NameStock.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            for (int i = 0; i < soNgay; i++)
            {
                row = "";
                foreach (List<float> list in listPriceOfStock)
                    row += (float)Math.Round(list[i], 1) + ",";
                row = row.Substring(0, row.Length - 1);
                listcontent.Insert(0, row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_PriceStock.txt", listcontent);
        }

        public static void Testing_BackTest_Stock_ConvexOptimation(List<string> nameStockPortfolio
                                    , int soNgay, ref List<float> listAvg, ref List<float> listStd)
        {
            List<string> listcontent = new List<string>();
            List<string> listStock = new List<string>();

            List<float> listResult = new List<float>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();

            List<List<float>> listPriceOfStock = new List<List<float>>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAvg\tStd");
            listcontent.Add("-----------------------");
            int count = 0;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date && nameStockPortfolio.Contains(cp.TenCoPhieu))
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Add(listTemp[i]);

                    if (count < 200) /// số lượng cổ phiếu
                    {
                        count++;
                        listPriceOfStock.Add(new List<float>());
                        foreach (float val in listvalue)
                            listPriceOfStock[listPriceOfStock.Count - 1].Add((float)Math.Round(val, 1));

                        listPriceOfStock[listPriceOfStock.Count - 1] = CoreFunctions.Xuly_DaoNguocList(listPriceOfStock[listPriceOfStock.Count - 1]);
                        List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listPriceOfStock[listPriceOfStock.Count - 1]);
                        avg = CoreFunctions.Tk_GetAverage(DailyReturns);
                        std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                        listAvg.Add(avg);
                        listStd.Add(std);
                        listStock.Add(cp.TenCoPhieu);
                        avg = (float)Math.Round(avg, 6);
                        std = (float)Math.Round(std, 6);
                        listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                    }
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);

            #region Testing
            // xây dựng ma trận pearson coeff, array mean(avg)và tên stock
            //float[,] matrix = new float[listStock.Count, listStock.Count];
            //float temp = 0f;
            //for (int i = 0; i < listStock.Count; i++)
            //{
            //    /// đường chéo chính
            //    matrix[i, i] = (float)Math.Pow(listStd[i], 2);
            //    for (int j = i + 1; j < listStock.Count; j++)
            //    {
            //        temp = CoreFunctions.MR_TinhPearsonCorrelationCoefficient(listPriceOfStock[i], listPriceOfStock[j]);
            //        matrix[i, j] = temp;
            //        matrix[j, i] = temp;
            //    }
            //}

            //listcontent = new List<string>();
            //string row = "";
            //for (int i = 0; i < listStock.Count; i++)
            //{
            //    row = "";
            //    for (int j = 0; j < listStock.Count; j++)
            //        row += (float)Math.Round(matrix[i, j], 3) + ",";

            //    row = row.Substring(0, row.Length - 1);
            //    listcontent.Add(row);
            //}
            //CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_MatrixPearsonCoeff.txt", listcontent);
            #endregion

            listcontent = new List<string>();
            string row = "";
            foreach (string name in listStock)
                row += name + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_NameStock.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            int length = listPriceOfStock[0].Count;
            for (int i = 0; i < length; i++)
            {
                row = "";
                foreach (List<float> list in listPriceOfStock)
                    row += (float)Math.Round(list[i], 1) + ",";
                row = row.Substring(0, row.Length - 1);
                listcontent.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_PriceStock.txt", listcontent);
        }

        public static void Testing_BackTest_Stock_ConvexOptimation_Volality(List<string> nameStockPortfolio
                                    , int soNgay, ref List<float> listVolality, ref List<float> listStd)
        {
            List<string> listcontent = new List<string>();
            List<string> listStock = new List<string>();

            List<float> listResult = new List<float>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();

            List<List<float>> listPriceOfStock = new List<List<float>>();
            listVolality = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float volality, std;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tVol\tStd");
            listcontent.Add("-----------------------");
            int count = 0;
            foreach (CoPhieu cp in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date && nameStockPortfolio.Contains(cp.TenCoPhieu))
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Add(listTemp[i]);

                    if (count < 200) /// số lượng cổ phiếu
                    {
                        count++;
                        listPriceOfStock.Add(new List<float>());
                        foreach (float val in listvalue)
                            listPriceOfStock[listPriceOfStock.Count - 1].Add((float)Math.Round(val, 1));

                        listPriceOfStock[listPriceOfStock.Count - 1] = CoreFunctions.Xuly_DaoNguocList(listPriceOfStock[listPriceOfStock.Count - 1]);
                        List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listPriceOfStock[listPriceOfStock.Count - 1]);
                        volality = cp.TinhVolality();
                        std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                        listVolality.Add(volality);
                        listStd.Add(std);
                        listStock.Add(cp.TenCoPhieu);                   
                        std = (float)Math.Round(std, 6);
                        listcontent.Add(cp.TenCoPhieu + "\t" + volality + "\t" + std);
                    }
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);

            listcontent = new List<string>();
            string row = "";
            foreach (string name in listStock)
                row += name + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_NameStock.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            int length = listPriceOfStock[0].Count;
            for (int i = 0; i < length; i++)
            {
                row = "";
                foreach (List<float> list in listPriceOfStock)
                    row += (float)Math.Round(list[i], 1) + ",";
                row = row.Substring(0, row.Length - 1);
                listcontent.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_PriceStock.txt", listcontent);
        }

        public static void Testing_RSI()
        {
            int count_morethan70 = 0, count_lessthan30 = 0, count_05 = 0, count_other = 0, sum;
            float score;

            List<string> listNgayGiaoDich = new List<string>();
            List<List<float>> listResult = new List<List<float>>();
            List<string> listFile = new List<string>();
            foreach (CoPhieu cp in ShareData.danhsachCoPhieu.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listNgayGiaoDich = cp.DanhSachNgayGiaoDich_String;
                    break;
                }


            for (int i = 0; i < 600; i++)
            {
                count_morethan70 = 0; count_lessthan30 = 0; count_05 = 0; count_other = 0;
                foreach (CoPhieu cp in ShareData.danhsachCoPhieu.DanhSachCoPhieu_List)
                {
                    if (!cp.DanhSachNgayGiaoDich_String.Contains(listNgayGiaoDich[i])
                        || !cp.DanhSachNgayGiaoDich_String.Contains(listNgayGiaoDich[i + 15]))
                        continue;                    

                    if (cp.DanhSachNgayGiaoDich.Count > 100)
                    {                        

                        score = cp.TinhDanhSachChiSo_RelativeStrengIndex_RSI(14, i);
                        if (score >= 70f) count_morethan70++;
                        else if (score >= 50f) count_05++;
                        else if (score <= 30f) count_lessthan30++;
                        else count_other++;
                    }
                }

                sum = count_morethan70 + count_05 + count_lessthan30 + count_other;
                List<float> listTemp = new List<float>();
                listTemp.Add((float)Math.Round((float)count_morethan70 / sum * 100, 0));
                listTemp.Add((float)Math.Round((float)count_05 / sum * 100, 0));
                listTemp.Add((float)Math.Round((float)count_lessthan30 / sum * 100, 0));
                listTemp.Add((float)Math.Round((float)count_other / sum * 100, 0));

                listResult.Add(listTemp);
            }
            string str = "";
            listFile.Add("CP\t\t>70%\t>50%\t>30%\tOther");
            listFile.Add("-------------------------------------------------------");
            for (int i = 0; i < listResult.Count; i++)
            {
                str = listNgayGiaoDich[i] + "\t";
                foreach (float f in listResult[i])
                    str += f.ToString() + "\t";
                listFile.Add(str);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_RSI.txt", listFile);
        }

        public static void Testing_RSI_TimGanNhat(float abovePercent = 0.98f)
        {
            List<string> listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath  
                + @"\HOSE\Testing_RSI.txt");
            List<string> listResult = new List<string>();
            listFile.RemoveAt(0);
            listFile.RemoveAt(0);
            List<float> sample = new List<float>();
            List<float> Tsample = new List<float>();

            List<float> pattern = new List<float>();
            List<float> Tpattern = new List<float>();
            float score;
            string str = ""; ;
            string[] p = listFile[0].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 1; i < p.Length; i++)            
                sample.Add(float.Parse(p[i]));

            for (int i = 1; i < listFile.Count; i++)
            {
                pattern = new List<float>();
                p = listFile[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                for (int j = 1; j < p.Length; j++)
                    pattern.Add(float.Parse(p[j]));

                score = CoreFunctions.MR_TinhCosineSimilar(sample, pattern);
                if (score >= abovePercent)
                {
                    str = p[0] + "\t\t" + (float)Math.Round(score, 3) + "\t\t";

                    for (int j = 1; j <= 3; j++)
                    {
                        string[] fsample = listFile[j].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                        string[] fpattern = listFile[i + j].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                        Tsample = new List<float>();
                        Tpattern = new List<float>();
                        for (int k = 1; k < fsample.Length; k++)
                        {
                            Tsample.Add(float.Parse(fsample[k]));
                            Tpattern.Add(float.Parse(fpattern[k]));
                        }

                        score = CoreFunctions.MR_TinhCosineSimilar(Tsample, Tpattern);
                        if (score < abovePercent)
                            break;
                        str += (float)Math.Round(score, 3) + "\t\t";
                    }
                    if (score < abovePercent)
                        continue;
                    listResult.Add(str);
                }
            }
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\Testing_RSI_Matching.txt", listResult);
        }

        public static void Testing_HienTuongGia()
        {
            float XanhVoDoLong = 0f, DoVoXanhLong = 0f;
            ShareData.danhsachCoPhieu.Testing_HienTuongGia(ref XanhVoDoLong, ref DoVoXanhLong);
            Console.WriteLine("Xanh Vo Do Long: " + (float)Math.Round(XanhVoDoLong, 2));
            Console.WriteLine("Do Vo Xanh Long: " + (float)Math.Round(DoVoXanhLong, 2));
        }

        public static void Testing_TestMyPortfolio()
        {
            List<string> listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath 
                + @"\HOSE\BackTest_MyPortfolioTest.txt");
            string[] part = listFile[0].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); ;
            string dateBegin = part[0], dateEnd = part[1];
            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_MaxAllocationPortfolio.txt");
            List<string> listNameCP = new List<string>();
            List<float> listPercent = new List<float>();
            foreach (string item in listFile)
            {
                part = item.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                listNameCP.Add(part[0]);
                listPercent.Add(float.Parse(part[1]));
            }

            float value = danhsachCoPhieu.Xuly_TangTruongGia(listNameCP, listPercent, dateEnd, dateBegin);
            listFile = new List<string>();
            listFile.Add(dateBegin + "\t" + dateEnd);
            listFile.Add("Value: " + value);

            foreach(CoPhieu vnindex in danhsachCoPhieu.DanhSachCoPhieu_List)
                if (vnindex.TenCoPhieu == "^VNINDEX")
                {
                    listFile.Add("Value vnindex: " + vnindex.Xuly_TangTruongGiaDongCua(dateEnd, dateBegin));
                    break;
                }

            listFile.Add("Portfolio:");
            for (int i = 0; i < listNameCP.Count; i++)            
                listFile.Add(listNameCP[i] + ":" + listPercent[i]);

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_MyPortfolioTest.txt", listFile);
        }

        public static void Test()
        {
            List<string> listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\CK_HOSE.txt");
            List<string> listContent = new List<string>();
            foreach (string line in listFile)
                listContent.Add(line.Trim().Replace("\t", ""));

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\", "CK_HOSE.txt", listContent);
        }

        public static void Test_python()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            Process process;

            string script = "";

            startInfo.UseShellExecute = false;

            startInfo.FileName = "testbatch.bat";
            startInfo.Arguments = script;
            startInfo.CreateNoWindow = true;

            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;

            process = new Process();
            process.StartInfo = startInfo;
            process.Start();

            StreamReader r = process.StandardOutput;
            String result = r.ReadToEnd();

            List<string> content = new List<string>();
            content.Add(result);
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath, @"\Output.txt", content);
        }
    }
}
